package pers.ljf.escloud.service.modules.app.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import pers.ljf.escloud.common.dto.OSSClientInfo;
import pers.ljf.escloud.common.req.DepartmentSaveReq;
import pers.ljf.escloud.common.req.EntSaveRequest;
import pers.ljf.escloud.common.req.GetClientReq;
import pers.ljf.escloud.common.utils.FileUtils;
import pers.ljf.escloud.dao.entity.app.BucketDept;
import pers.ljf.escloud.dao.entity.app.Department;
import pers.ljf.escloud.dao.entity.app.Enterprise;
import pers.ljf.escloud.dao.entity.app.User;
import pers.ljf.escloud.dao.entity.sys.SysUserEntity;
import pers.ljf.escloud.dao.mapper.app.DepartmentMapper;
import pers.ljf.escloud.service.modules.app.*;
import pers.ljf.escloud.service.modules.sys.SysUserService;

import javax.annotation.Resource;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author laijinfan1
 * @since 2022-02-14
 */
@Service
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements DepartmentService {

    @Resource
    private SysUserService sysUserService;

    @Resource
    private UserService appUserService;

    @Resource
    private EnterpriseService enterpriseService;

    @Override
    public void save(EntSaveRequest form) {
        Department department = new Department();
        Assert.isTrue(!StringUtils.isEmpty(form.getAdminAccount()), "账号不可为空");
        User user = appUserService.getOne(new QueryWrapper<User>().eq("username", form.getAdminAccount()));
        Assert.isTrue(user != null, "部门主管不存在");
        department.setDirectorId(user.getId());

        Assert.isTrue(!StringUtils.isEmpty(form.getAdminAccount()), "企业名未知");
        Enterprise enterprise = enterpriseService.getOne(new QueryWrapper<Enterprise>().eq("name", form.getName()));
        Assert.isTrue(enterprise != null, "部门的企业不存在");
        department.setEnterpriseId(enterprise.getId());
        department.setEnterpriseName(enterprise.getName());
        department.setName(form.getName());
        department.setFullPathName(form.getName());

        department.setParentId(0L);
        save(department);
        //补充用户部门信息
        Department deptDB = getOne(new QueryWrapper<Department>().eq("enterprise_name", form.getName()).eq("parent_id", 0L));
        Assert.isTrue(deptDB != null, "找不到新建的部门");
        deptDB.setFullPathCode(deptDB.getId() + "");
        updateById(deptDB);
        user.setDeptId(deptDB.getId());
        appUserService.updateById(user);
    }

    @Override
    public void updateSpace(Long userId, long sizeMB) {
        User user = appUserService.getById(userId);
        Long deptId = user.getDeptId();
        Department department = getById(deptId);
        long spaceNew = department.getSpaceUsed() + sizeMB < 0 ? 0 : department.getSpaceUsed() + sizeMB;
        Assert.isTrue((spaceNew) <= department.getSpaceAmount(), "部门新已用空间超出限制");
        department.setSpaceUsed(spaceNew);
        updateById(department);
    }

    public void updateDeptSpace(Long deptId, long sizeMB) {
        Department department = getById(deptId);
        long spaceNew = department.getSpaceUsed() + sizeMB < 0 ? 0 : department.getSpaceUsed() + sizeMB;
        Assert.isTrue((spaceNew) <= department.getSpaceAmount(), "部门新已用空间超出限制");
        department.setSpaceUsed(spaceNew);
        updateById(department);
    }

    @Override
    public List<Department> list(Long userId, Map<String, Object> params) {
        String deptName = (String) params.get("deptName");
        Long entId = sysUserService.getById(userId).getEntId();
        Enterprise enterprise = enterpriseService.getById(entId);
        List<Department> departments = this.list(new QueryWrapper<Department>()
                .like(org.apache.commons.lang3.StringUtils.isNotBlank(deptName), "name", deptName)
                .eq("enterprise_id", enterprise.getId()));
        for (Department department : departments) {
            Long directorId = department.getDirectorId();
            User admin = appUserService.getById(directorId);
            department.setAdminUserName(admin.getUsername());
        }
        return departments;
    }

    @Resource
    private FileService fileService;

    @Resource
    private BucketService bucketService;

    @Resource
    private BucketDeptService bucketDeptService;
    @Override
    @Transactional
    public void save(DepartmentSaveReq req) {
        Department dept = new Department();
        BeanUtils.copyProperties(req, dept);
        //管理员更新
        User adminUser = appUserService.getOne(new QueryWrapper<User>().eq("username", req.getAdminUserName()));
        Assert.isTrue(adminUser != null, "管理员不存在");
        dept.setDirectorId(adminUser.getId());
        //父部门更新
        Department newParent = getById(req.getParentId());
        Assert.isTrue(newParent != null, "父部门不存在");
        dept.setParentId(req.getParentId());
        dept.setParentDeptName(newParent.getName());

        String newFullPathName = newParent.getFullPathName() + "/" + req.getName();
        dept.setFullPathName(newFullPathName);
        if (req.getId() != null) {
            Department oldDeptDB = getById(req.getId());
            //校验空间大小
            Assert.isTrue(oldDeptDB != null && oldDeptDB.getSpaceUsed() <= req.getSpaceAmount(), "部门新空间必须大于已用空间");
            OSSClientInfo client = bucketService.getClient(GetClientReq.builder().deptId(req.getId()).build());
            if (req.getParentId() != null && !Objects.equals(oldDeptDB.getParentId(), req.getParentId())) {
                //移动部门文件
                long sizeMB = fileService.moveObject(client, oldDeptDB.getFullPathName(), newParent.getFullPathName() + "/" + req.getName());
                //更新空间大小变化
                fileService.updateSizeFromOldToNew(oldDeptDB.getParentId(), newParent.getId(), sizeMB);
            }
        } else {
            //创建新部门的文件夹
            OSSClientInfo info = bucketService.getClient(GetClientReq.builder().deptId(req.getParentId()).build());
            File tmpFile = FileUtils.getNetUrlHttps("https://ljf-gulimall.oss-cn-beijing.aliyuncs.com/img/20210607163831.png");
            info.getClient().putObject(info.getBucketName(), newFullPathName + "/" + "net_url2870800544618991248a04fcf12-9b80-4256-9e05-b1b2c2660066.png", tmpFile);
//            info.getClient().deleteObject(info.getBucketName(),newFullPathName + "/" + tmpFile.getName());
        }
        SysUserEntity sysUser = (SysUserEntity)SecurityUtils.getSubject().getPrincipal();
        dept.setEnterpriseId(sysUser.getEntId());
        dept.setEnterpriseName(sysUser.getEntName());
        saveOrUpdate(dept);
        Department newDeptDB = getOne(new QueryWrapper<Department>().eq("full_path_name", newFullPathName));
        newDeptDB.setFullPathCode(newParent.getFullPathCode() + "/" + newDeptDB.getId());
        newDeptDB.setFullPathName(newFullPathName);
        updateById(newDeptDB);

        BucketDept newBucketDept = bucketDeptService.getOne(new QueryWrapper<BucketDept>().eq("dept_id", newDeptDB.getId()));
        BucketDept bucketDept = new BucketDept();
        if (newBucketDept != null) {
            bucketDept.setId(newBucketDept.getId());
        }
        BucketDept parentBuckDept = bucketDeptService.getOne(new QueryWrapper<BucketDept>().eq("dept_id", newParent.getId()));
        bucketDept.setBucketId(parentBuckDept.getBucketId());
        bucketDept.setDeptId(newDeptDB.getId());
        bucketDeptService.saveOrUpdate(bucketDept);
    }
}
